package com.loong.musicdemo.ui.find.activity;

import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.loong.musicdemo.R;
import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.util.dataDeal.MusicDeal;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

public class DailyRecommendActivity extends AppCompatActivity {
    private RecyclerView recommendRecyclerView;
    private SmartRefreshLayout loading;
    List<Song> songList = new ArrayList<>();
    List<String> ids;
    RecommendSongsAdapter adapter;
    private ProgressBar progressBar;
    private RequestOptions requestOptions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daily_recommend);
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        recommendRecyclerView = findViewById(R.id.recommend_recycler_view);
        progressBar = findViewById(R.id.progressBar);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("新歌速递");
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        //设置圆角图片
        requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.temp);
        requestOptions.circleCropTransform();
        requestOptions.bitmapTransform( new RoundedCorners(10));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recommendRecyclerView.setLayoutManager(layoutManager);
        adapter = new RecommendSongsAdapter(songList, getApplicationContext());
        recommendRecyclerView.setAdapter(adapter);
        new Thread(() -> {
            ids = MusicDeal.getDailyNewSongsID();
            if (ids != null) {
                List<Song> songs = new ArrayList<>();
                if (ids.size() <= 10) {
                    songs = MusicDeal.getSongListByIds(ids);
                } else {
                    List<String> list = ids.subList(0, 10);
                    ids = ids.subList(10, ids.size());
                    songs = MusicDeal.getSongListByIds(list);
                }
                songList.addAll(songs);
                runOnUiThread(() -> {
                    adapter.notifyDataSetChanged();
                    progressBar.setVisibility(View.GONE);
                });
            }
        }).start();
        loading = findViewById(R.id.refresh_play_list);
        loading.setEnableRefresh(false);
        loading.autoLoadmore();
        loading.setOnLoadmoreListener(refreshlayout -> {
            new ShowSongsTask().execute();//加载后续数据
        });
    }

    class RecommendSongsAdapter extends RecyclerView.Adapter<RecommendSongsAdapter.ViewHolder> {
        List<Song> songList;
        Context context;

        public RecommendSongsAdapter(List<Song> songList, Context context) {
            this.songList = songList;
            this.context = context;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.daily_recommend_item, parent, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Song song = songList.get(position);
            holder.name.setText(song.getName());
            holder.info.setText(song.getSingerName() + "-" + song.getAlbumName());
            Glide.with(context).load(song.getPicUrl()).apply(requestOptions).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.image);
        }

        @Override
        public int getItemCount() {
            return songList.size();
        }

        private  class ViewHolder extends RecyclerView.ViewHolder {
            TextView name, info;
            ImageView image;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.recommend_song_name);
                image = itemView.findViewById(R.id.recommend_song_img);
                info = itemView.findViewById(R.id.recommend_song_info);
            }
        }
    }


    @SuppressLint("StaticFieldLeak")
    class ShowSongsTask extends AsyncTask<Song, Void, List<Song>> {

        @Override
        protected List<Song> doInBackground(Song... songs) {
            if (ids.size() <= 10) {
                List<Song> list;
                list = MusicDeal.getSongListByIds(ids);
                return list;
            } else {
                List<String> list = ids.subList(0, 10);
                ids = ids.subList(10, ids.size());
                return MusicDeal.getSongListByIds(list);
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<Song> songs) {
            super.onPostExecute(songs);
            if(songs.size()==0){
                loading.setEnableRefresh(false);
            }else {
                songList.addAll(songs);
                adapter.notifyDataSetChanged();
                loading.finishLoadmore();
            }

        }
    }

    /**
     * 添加返回菜单功能
     *
     * @param item 菜单
     * @return 是否正确
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;//返回前一个活动
        }
        return super.onOptionsItemSelected(item);
    }
}
